const httpsFns = require("./httpsFns");
const fs = require("fs");
const path = require("path");

// 下载图片
const downloadImage = async function (url, filePath, docxFile, pObj) {
  await httpsFns.httpsGet(
    url,
    {
      headers: {
        Referer: "https://science.liankexue.cn/",
      },
    },
    (response, resolve) => {
      response.setEncoding("binary");
      let imageBuffer = "";
      response.on("data", (chunk) => {
        imageBuffer += chunk;
      });
      response.on("end", () => {
        const cwd = process.cwd();
        const relativePath = path.join(
          "temp",
          `${+new Date()}_downloadedImage.png`
        );
        fs.writeFileSync(path.join(cwd, relativePath), imageBuffer, "binary");
        pObj.addImage(path.join(cwd, relativePath));
        let out = fs.createWriteStream(filePath);
        out.on("error", function (err) {
          console.log(err);
        });
        docxFile.generate(out);
        resolve(true);
      });
    }
  );
};

module.exports = {
  downloadImage,
};
